package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.dto.WmNewsDto;
import com.heima.media.dto.WmNewsPageDto;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author syl
 * @since 2022-06-28
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Autowired
    @Lazy
    private IAuditService auditService;

    @Override
    public ResponseResult listByCondition(WmNewsPageDto dto) {
        User user = UserThreadLocalUtil.get();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
//        做各种条件查询
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        if(dto.getStatus()!=null){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        if(dto.getChannelId()!=null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }

        if(dto.getChannelId()!=null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }

        if(dto.getBeginPubDate()!=null && dto.getEndPubDate()!=null){
//            WmNews::getPublishTime 大于等于  getBeginPubDate
//            WmNews::getPublishTime 小于等于  getEndPubDate
            queryWrapper.ge(WmNews::getPublishTime,dto.getBeginPubDate());
            queryWrapper.le(WmNews::getPublishTime,dto.getEndPubDate());
        }
        if(StringUtils.isNotBlank(dto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }

        queryWrapper.eq(WmNews::getUserId,user.getUserId());
//        隐藏条件：登录人
        queryWrapper.orderByDesc(WmNews::getPublishTime);
//                自媒体文章发布时间 倒序 排序

        Page<WmNews> page = new Page<>(dto.getPage(),dto.getSize());

        Page<WmNews> page1 = this.page(page, queryWrapper);

        return new PageResponseResult(dto.getPage(),dto.getSize(),page1.getTotal(),page1.getRecords());
    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {
        User user = UserThreadLocalUtil.get();
        if (user==null) { //判断是否有登录人
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
 //        保存自媒体文章
//        先判断是否有id  如果有就是修改，如果没有就是新增
        if(dto.getId()!=null){  //  如果有就是修改
//            删除已关联素材的关系
            deleteRelation(dto.getId());
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews); // spring下的BeanUtils
//        wmNews.setType(dto.getType());
        wmNews.setUserId(user.getUserId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setStatus(dto.getStatus());// TODO   提交为1  草稿为0
//        wmNews.setReason(); //审核失败的原因 ，先不处理
//        wmNews.setArticleId(); // app文章的id，等审核通过后 远程调用article微服务生成一个app文章 返回app文章的id ，先不处理
        List<ImageDto> coverImageList = dto.getImages();

        wmNews.setImages(JSON.toJSONString(coverImageList)); // TODO
        wmNews.setEnable(true);

//        文章内容格式：
//       " [{"type":"text","value":"自古人生有三大喜事"},
//        {"type":"image","value":"http://192.168.85.143:9000/heima/92f3fff2-b7ec-4ade-8798-40c896320c18.jpeg","id":267},
//        {"type":"text","value":"同学高考查询分数为0分，是怎么回事？"},
//        {"type":"image","value":"http://192.168.85.143:9000/heima/4e342011-dd0c-4a5b-8005-ad065ab43056.jpeg","id":264},
//        {"type":"text","value":"为保护考生隐私，出现“高考屏蔽生”"},
//        {"type":"image","value":"http://192.168.85.143:9000/heima/5ab971f2-8833-4d3f-8842-6848b7c6d50a.jpeg","id":266}]"
//        从文章内容中获取所有的图片，构建到一个List集合中
        List<ImageDto> contentImagesList = getImageListFromContent(dto.getContent());
        if(dto.getType()==-1){ //封面图片是要自动从文章内容中获取
            int size = contentImagesList.size();
//            如果文章内容没有图片
            if(size ==0){
                wmNews.setType(0);
//                [{"id":256,"url":"http://192.168.85.143:9000/heima/32fbeafb-d6d3-4100-9b53-040fa4aab2cd.png"},
//                {"id":257,"url":"http://192.168.85.143:9000/heima/c289ae2a-89ea-4d3f-89a4-8b512db07645.png"},
//                {"id":258,"url":"http://192.168.85.143:9000/heima/a88f84e2-0678-42bf-8d55-d38ea450b454.png"}]
                coverImageList  = contentImagesList;

            }else if(size>0&&size<3){
                //            如果文章内容有少于3个图片
                wmNews.setType(1);
                coverImageList = contentImagesList.subList(0, 1);
            }else  if(size>=3){
 //            如果文章内容多于或等于3个图片
                wmNews.setType(3);
                coverImageList = contentImagesList.subList(0, 3);
            }
            wmNews.setImages(JSON.toJSONString(coverImageList));
        }

        this.saveOrUpdate(wmNews); //如果有id就是update，如果没有ID就是save

//        wmNews.setStatus(dto.getStatus());// TODO   提交为1  草稿为0
//        判断是否为草稿
        if(dto.getStatus()==1){
//            关联内容中的图片与素材的关系
//            contentImagesList
            saveRelation(contentImagesList,wmNews.getId(),0);
//      关联封面图片与素材的关系    coverImageList
            saveRelation(coverImageList,wmNews.getId(),1);

//            调用自媒体文章审核的方法
            auditService.audit(wmNews); //这个方法比较耗时的  1、阿里云文本审核 2、阿里云图片审核 3、feign保存app文章
//            因为上边这个方法比较消耗时间，所以可以采用异步的方案：
//            异步有两种做法：1、借助MQ  2、使用多线程
        }

        return ResponseResult.okResult();
    }


    private void saveRelation(List<ImageDto> contentImagesList, Integer newsId, int type) {
        int ord = 0;
        for (ImageDto imageDto : contentImagesList) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(imageDto.getId());
            wmNewsMaterial.setNewsId(newsId);
            wmNewsMaterial.setType(type);
            wmNewsMaterial.setOrd(ord);
            ord++;
            wmNewsMaterialService.save(wmNewsMaterial);
        }
    }

    //       " [{"type":"text","value":"自古人生有三大喜事"},
//        {"type":"image","value":"http://192.168.85.143:9000/heima/92f3fff2-b7ec-4ade-8798-40c896320c18.jpeg","id":267},
//        {"type":"text","value":"同学高考查询分数为0分，是怎么回事？"},
//        {"type":"image","value":"http://192.168.85.143:9000/heima/4e342011-dd0c-4a5b-8005-ad065ab43056.jpeg","id":264},
//        {"type":"text","value":"为保护考生隐私，出现“高考屏蔽生”"},
//        {"type":"image","value":"http://192.168.85.143:9000/heima/5ab971f2-8833-4d3f-8842-6848b7c6d50a.jpeg","id":266}]"
    private List<ImageDto> getImageListFromContent(String content) {
        List<ContentDto> contentDtoList = JSON.parseArray(content, ContentDto.class);
        List<ImageDto> imageDtoList = new ArrayList<>();
        for (ContentDto contentDto : contentDtoList) {
            if (contentDto.getType().equals("image")) {
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                imageDtoList.add(imageDto);
            }
        }
        return imageDtoList;
    }

    @Autowired
    private IWmNewsMaterialService wmNewsMaterialService;
//    就是根据自媒体文章id删除文章和素材之间的关系
    private void deleteRelation(Integer newsId) {
//        delete from wm_news_material where news_id=?
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getNewsId,newsId);
        wmNewsMaterialService.remove(queryWrapper);
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        User user = UserThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

//        1、先判断是否有文章id
        if(dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
//        2、再判断根据id是否能查询出对象
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//       3、判断这个自媒体文章是当前登录人发布的吗
        if (user.getUserId() != wmNews.getUserId()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
//       4、判断文章是否为发布状态
        if (wmNews.getStatus()!=9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        wmNews.setEnable(dto.getEnable()==1?true:false);   //true 1 上架 false0 下架
        this.updateById(wmNews);

        return ResponseResult.okResult();
    }
}
